<?php
namespace App\Mvc;
use \Phalcon\Events\Manager as EventsManager;

/**
 * 控制器调度服务
 * @package App\Mvc
 */
class Dispatcher extends \Phalcon\Mvc\Dispatcher {

    #region 属性

    /**
     * \Phalcon\Di 对象
     * @var \Phalcon\Di
     */
    protected $di;

    /**
     * \Phalcon\Config 对象
     * @var \Phalcon\Config
     */
    protected $config;

    #endregion

    /**
     * 构造函数
     * @param \Phalcon\Config $config 配置信息对象
     * @param  \Phalcon\Di $di \Phalcon\Di 对象
     */
    function __construct(\Phalcon\Config $config, \Phalcon\Di $di) {
        $this->config = $config;
        $this->di = $di;
    }

    #region 将事件绑定到事件管理器

    /**
     * 将事件绑定到事件管理器
     */
    function attach() {
        // 创建一个事件管理
        $eventsManager = new EventsManager();

        // 将循环调度事件绑定到事件管理器
        $eventsManager->attach("dispatch", new \App\Plugins\DispatchPlugin());

        $this->setEventsManager($eventsManager);
    }

    #endregion

    #region 处理调度对象

    /**
     * 处理调度器对象
     */
    function setDispatcher() {
        /*$moduleName = "v2";

            // 获取请求头信息
            $headers = \App\Helpers\CommonUtils::getAllHeaders();
            if ($headers && key_exists("Accept", $headers)) {
                $accept = $headers["Accept"];
                $start = strpos($accept, "ver");
                if ($start !== false) {
                    $vals = substr($accept, $start);
                    $versions = explode("=", $vals);
                    if ($versions && count($versions) == 2) {
                        $version = strtolower($versions[1]);
                        $moduleName = strpos($version, ".") !== false ? str_replace(".", "_", $version) : $version;
                    }
                }
            }*/
        //获取客户端能够接收的内容类型
        /**
         * @var \Phalcon\Mvc\Router $router
         */
        $router = $this->di->getShared("router");
        $moduleName = $router->getModuleName();
        $this->setModuleName($moduleName);
        $this->setControllerName($router->getControllerName());
        $this->setActionName($router->getActionName());
        $this->setParams($router->getParams());
        $moduleName = strtoupper($moduleName);
        $this->setDefaultNamespace("App\\{$moduleName}\\Controllers");
    }

    #endregion

}